package com.rc.saas.tenant.service.tenant;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.constant.WebConstant;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.mapper.tenant.TenantMapper;
import com.rc.saas.tenant.mapper.operator.TenantOperatorMapper;
import com.rc.saas.tenant.mapper.tenant.TenantUserMapper;
import com.rc.saas.tenant.model.tenant.*;
import com.rc.saas.tenant.model.operator.TenantOperator;
import com.rc.saas.tenant.search.tenant.TenantUserSearch;
import com.rc.saas.tenant.vo.tenant.TenantUserVo;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.crazycake.shiro.RedisSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class TenantUserServiceImpl implements TenantUserService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private TenantOperatorMapper tenantOperatorMapper;

    @Autowired
    private TenantUserMapper tenantUserMapper;

    @Override
    public TenantUserMapper getMapper() {
        return tenantUserMapper;
    }

    @Override
    public void createUser(TenantUser user) {
        //加密密码
        user.setPassword(MD5Utils.encrypt(user.getLoginName(), user.getPassword()));
        insertSelective(user);

        //新增关联
        //if (user.getTenantRoleId() > 0) {
        //    TenantUserRole roleUser = new TenantUserRole();
        //    roleUser.setTenantRoleId(user.getTenantRoleId());
        //    roleUser.setTenantUserId(user.getTenantUserId());
        //    tenantUserRoleMapper.insertSelective(roleUser);
        //}
    }

    @Override
    public void updatedUserAndTenantPassword(TenantUser user, String newPassword) {
        String saltPassword = MD5Utils.encrypt(user.getLoginName(), newPassword);

        //更新为新密码，同时更新原来的tenant或tenant_operator密码
        TenantUser updateUser = new TenantUser();
        updateUser.setTenantUserId(user.getTenantUserId());
        updateUser.setPassword(saltPassword);
        tenantUserMapper.updateByPrimaryKeySelective(updateUser);

        if (user.getUserType().equals(WebConstant.STATUS_ZERO)) {//运营商
            Tenant updateTenant = new Tenant();
            updateTenant.setTenantCode(user.getTenantCode());
            updateTenant.setPassword(saltPassword);
            tenantMapper.updateByPrimaryKeySelective(updateTenant);
        } else if (user.getUserType().equals(WebConstant.STATUS_ONE)) {//分销商
            TenantOperator updateOperator = new TenantOperator();
            updateOperator.setTenantOperatorCode(user.getTenantOperatorCode());
            updateOperator.setPassword(saltPassword);
            tenantOperatorMapper.updateByPrimaryKeySelective(updateOperator);
        } else if (user.getUserType().equals(WebConstant.STATUS_TWO)) {//企业帐户
            //EnterpriseMember updateEnterprise = new EnterpriseMember();
            //updateEnterprise.setEnterpriseId(user.getEnterpriseId());
            //updateEnterprise.setPassword(saltPassword);
            //enterpriseMemberMapper.updateByPrimaryKeySelective(updateEnterprise);
        }
    }

    @Override
    public void updatedUserAndTenantMobile(TenantUser user, String newMobile) {
        //更新为新手机，同时更新原来的tenant或tenant_operator手机
        TenantUser newUser = new TenantUser();
        newUser.setTenantUserId(user.getTenantUserId());
        newUser.setMobile(newMobile);
        tenantUserMapper.updateByPrimaryKeySelective(newUser);

        if (user.getUserType().equals(WebConstant.STATUS_ZERO)) {//运营商
            Tenant newTenant = new Tenant();
            newTenant.setTenantCode(user.getTenantCode());
            newTenant.setPhone(newMobile);
            tenantMapper.updateByPrimaryKeySelective(newTenant);
        } else if (user.getUserType().equals(WebConstant.STATUS_ONE)) {//分销商
            TenantOperator newTenantOperator = new TenantOperator();
            newTenantOperator.setTenantOperatorCode(user.getTenantOperatorCode());
            newTenantOperator.setPhone(newMobile);
            tenantOperatorMapper.updateByPrimaryKeySelective(newTenantOperator);
        } else if (user.getUserType().equals(WebConstant.STATUS_TWO)) {//企业帐户
            //EnterpriseMember updateEnterprise = new EnterpriseMember();
            //updateEnterprise.setEnterpriseId(user.getEnterpriseId());
            //updateEnterprise.setPassword(saltPassword);
            //enterpriseMemberMapper.updateByPrimaryKeySelective(updateEnterprise);
        }
    }

    @Override
    public void updatedUserAndTenantEmail(TenantUser user, String newEmail) {
        //更新为新邮箱，同时更新原来的tenant或tenant_operator邮箱
        TenantUser newUser = new TenantUser();
        newUser.setTenantUserId(user.getTenantUserId());
        newUser.setEmail(newEmail);
        tenantUserMapper.updateByPrimaryKeySelective(newUser);

        //if (user.getUserType().equals(WebConstant.STATUS_ZERO)) {//运营商
        //    Tenant newTenant = new Tenant();
        //    newTenant.setTenantCode(user.getTenantCode());
        //    tenantMapper.updateByPrimaryKeySelective(newTenant);
        //} else if (user.getUserType().equals(WebConstant.STATUS_ONE)) {//分销商
        //    TenantOperator newTenantOperator = new TenantOperator();
        //    newTenantOperator.setTenantOperatorCode(user.getTenantOperatorCode());
        //    tenantOperatorMapper.updateByPrimaryKeySelective(newTenantOperator);
        //} else {//企业用户
        //}
    }

    @Override
    public TenantUser findUserByExample(TenantUserExample example) {
        List<TenantUser> list = tenantUserMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public TenantUser selectByLoginName(String loginName) {
        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andLoginNameEqualTo(loginName);
        List<TenantUser> tenantUsers = tenantUserMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(tenantUsers)) {
            return tenantUsers.get(0);
        }
        return null;
    }

    @Override
    public TenantUser selectByMobile(String mobile) {
        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andMobileEqualTo(mobile);
        List<TenantUser> tenantUsers = tenantUserMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(tenantUsers)) {
            return tenantUsers.get(0);
        }
        return null;
    }

    @Override
    public List<OnlineUser> listOnlineUser(ApplicationContext ac) {
        RedisSessionDAO sessionDAO = (RedisSessionDAO) ac.getBean("redisSessionDAO");
        //获取在线用户信息
        Collection<Session> ss = sessionDAO.getActiveSessions();

        List<OnlineUser> list = new ArrayList<>();
        for (Session s : ss) {
            Object obj = s.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (obj != null) {
                SimplePrincipalCollection spc = (SimplePrincipalCollection) obj;
                if (spc.getPrimaryPrincipal() != null) {
                    TenantUser u = (TenantUser) spc.getPrimaryPrincipal();
                    //logger.info("CmsUser.........{}", u.getLoginName());

                    OnlineUser uu = new OnlineUser();
                    BeanUtils.copyProperties(u, uu);
                    uu.setSessionId(s.getId().toString());
                    uu.setHost(s.getHost());
                    uu.setStartTimestamp(s.getStartTimestamp());
                    uu.setLastAccessTime(s.getLastAccessTime());
                    uu.setTimeout(s.getTimeout());
                    //uu.setExpired(s.get);

                    list.add(uu);
                }
            }
        }
        return list;
    }

    @Override
    public PageInfo<TenantUser> selectUserByPage(TenantUser record, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TenantUser> list = tenantUserMapper.selectByEecord(record);
        return new PageInfo<TenantUser>(list);
    }

    @Override
    public TenantUser checkLoginNameExist(String loginName) {
        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andLoginNameEqualTo(loginName);
        List<TenantUser> list = tenantUserMapper.selectByExample(example);
        if (list.size() != 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public TenantUser checkPhoneExist(String phone) {
        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andMobileEqualTo(phone);
        List<TenantUser> list = tenantUserMapper.selectByExample(example);
        if (list.size() != 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public TenantUser checkTenantCodeExist(String tenantCode) {
        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode);
        List<TenantUser> list = tenantUserMapper.selectByExample(example);
        if (list.size() != 0) {
            return list.get(0);
        }
        return null;
    }


    @Override
    public List<TenantUser> listTenantUserByUserType(String userType) {
        return tenantUserMapper.listTenantUserByUserType(userType);
    }

    @Override
    public PageInfo<TenantUserVo> listPageTenantUser(TenantUserSearch tenantUserSearch) {
        PageHelper.startPage(tenantUserSearch.getOffset(), tenantUserSearch.getLimit());
        List<TenantUserVo> tenantUserList = tenantUserMapper.listPageTenantUser(tenantUserSearch);
        return new PageInfo<>(tenantUserList);
    }

    @Override
    public TenantUser selectUserByMobile(Long enterpriseId, String mobile) {
        if (enterpriseId == null || mobile == null) {
            return null;
        }

        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andEnterpriseIdEqualTo(enterpriseId).andMobileEqualTo(mobile);
        return tenantUserMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }
}
